package com._119yn.host.gst200.cansocket.codec;

import com._119yn.host.gst200.cansocket.message.CanFrame;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CanFrameDecoder extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof String s && s.contains("#")) {
            log.debug("RECV:{}", s);
            CanFrame canFrame;
            try {
                canFrame = decode(s);
            } catch (Exception e) {
                log.error(e.getMessage());
                canFrame = null;
            }
            if (canFrame != null) {
                ctx.fireChannelRead(canFrame);
            }
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    private static boolean valid(String s) {
        return s != null && s.contains("#");
    }

    private CanFrame decode(String lineData) {
        if (valid(lineData)) {
            return new CanFrame(lineData);
        } else {
            return null;
        }
    }

}
